package com.ruoyi.his.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.his.domain.OdsDoctorAll;
import com.ruoyi.his.domain.OdsHospitalAll;
import com.ruoyi.his.domain.vo.HisNurseExcelVo;
import com.ruoyi.his.domain.vo.HisNurseVo;
import com.ruoyi.his.domain.vo.OdsDoctorAllVo;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.his.mapper.HisNurseMapper;
import com.ruoyi.his.domain.HisNurse;
import com.ruoyi.his.service.IHisNurseService;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Alan
 * @date 2024-03-24
 */
@Service
public class HisNurseServiceImpl implements IHisNurseService
{
    @Autowired
    private HisNurseMapper hisNurseMapper;
    @Autowired
    private ISysUserService iUserService;
    @Autowired
    private SysDictDataMapper dictDataMapper;

    public List<HisNurse> makeList(List<HisNurse> list,String signature){
        List<HisNurse> result = new ArrayList<>();
        for(HisNurse item:list){
            if(StringUtils.isNotEmpty(item.getNurseId()) && StringUtils.isNotEmpty(item.getName())) {
                item.setSignature(signature);
                item.setUpdateTime(new Date());
                result.add(item);
            }
        }
        return result;
    }
    @Override
    public AjaxResult insertNure(HisNurseVo vo) {
        SysDictData pa = new SysDictData();
        //查询是否有签名
        pa.setDictType("his");
        pa.setStatus("0");
        pa.setDictValue(vo.getSignature());
        int count = dictDataMapper.selectByCount(pa);
        if (count==0)
        {
            return AjaxResult.error("没有签名未授权访问！");
        }
        //设置签名
        List<HisNurse> list = makeList(vo.getData(),vo.getSignature());
        if(list.size()==0){
            return AjaxResult.error("请传入必填参数！");
        }
        //批量插入
        hisNurseMapper.InsertOfList(list);
        //批量更新按身份证号
        hisNurseMapper.updateOfListIdCard(list);
        //批量更新按护士证号
        hisNurseMapper.updateOfListLicence(list);
        //批量更新按执业号
        hisNurseMapper.updateOfListSeniority(list);
        //批量更新按编号
        hisNurseMapper.updateOfListNid(list);
        //批量删除按编号只保留最早一条
        hisNurseMapper.deleteKeepOneByIdCard();
        hisNurseMapper.deleteKeepOneByNurseLicence();
        hisNurseMapper.deleteKeepOneBySeniority();
        hisNurseMapper.deleteKeepOneByNid();
        return AjaxResult.success();
    }

    public String registerNurseSelectRule(HisNurse hisNurse) {
        SysDictData param = new SysDictData();
        //查询是否有签名
        param.setDictType("his");
        param.setStatus("0");
        param.setDictValue(hisNurse.getSignature());
        int count = dictDataMapper.selectByCount(param);
        if (count==0)
        {
            return "没有签名未授权访问！";
        }
        if (StringUtils.isEmpty(hisNurse.getRegionCode())) {
            return "请选择辖区！";
        }
        if (StringUtils.isEmpty(hisNurse.getInstitutionName())) {
            return "请选择机构！";
        }
        if (StringUtils.isEmpty(hisNurse.getName())) {
            return "护士姓名不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getPhone())) {
            return "手机号码不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getIdCard())) {
            return "护士身份证号不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getSex())) {
            return "请选择护士性别！";
        }
        if (StringUtils.isEmpty(hisNurse.getBirthday())) {
            return "请选择出生日期！";
        }
        if (StringUtils.isEmpty(hisNurse.getAntecedent())) {
            return "学历不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getSpecialty())) {
            return "院校和专业不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getNurseSeniority())) {
            return "护士执业证书不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getNurselicence())) {
            return "护士资格证书不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getUsername())) {
            return "用户名不能为空！";
        }
        if (StringUtils.isEmpty(hisNurse.getPassword())) {
            return "密码不能为空！";
        }

        return null;
    }

    @Override
    public AjaxResult registerNurseSelect(HisNurse hisNurse) {
        String msg = registerNurseSelectRule(hisNurse);
        if(msg!=null){
            return AjaxResult.error(msg);
        }
        if(hisNurse.getReCount()==0) {
            if (StringUtils.isEmpty(hisNurse.getNurseId())) {
                return AjaxResult.error("请选择护士！");
            }
        }
        List<HisNurse> result2= hisNurseMapper.selectList(new LambdaQueryWrapper<HisNurse>().eq(HisNurse::getNurseId,hisNurse.getNurseId()).eq(HisNurse::getSignature,hisNurse.getSignature()));
        //通过用户名判断 判断用户是否存在
        String s = iUserService.checkUserNameUnique(hisNurse.getUsername());
        if(!(s.equals(UserConstants.UNIQUE))){
            return AjaxResult.error("用户名已经被注册了！");
        }
        //通过护士资格证号判断用户是否存在
        List<SysUser> lsuser = iUserService.selectUserBySe(hisNurse.getNurseSeniority());
        if(lsuser != null&&lsuser.size()>0){
            return AjaxResult.error("护士已经被注册了！");
        }
        //密码加密
        String password = SecurityUtils.encryptPassword(hisNurse.getPassword());
        SysUser sysUser = new SysUser();
        sysUser.setUserName(hisNurse.getUsername());
        sysUser.setPassword(password);
        sysUser.setUserType("9");
        sysUser.setSignature(hisNurse.getSignature());
        sysUser.setNurseId(hisNurse.getNurseId());
        sysUser.setNurseSeniority(hisNurse.getNurseSeniority());
        sysUser.setUpdateTime(new Date());

        //向数据库里面插入数据
        int j = iUserService.insertUser(sysUser);
        if(j>0){
            List<HisNurse> list = new ArrayList<>();
            list.add(hisNurse);
            //批量插入
            hisNurseMapper.InsertOfList(list);
            //批量更新按身份证号
            hisNurseMapper.updateOfListIdCard(list);
            //批量更新按护士证号
            hisNurseMapper.updateOfListLicence(list);
            //批量更新按执业号
            hisNurseMapper.updateOfListSeniority(list);
            //批量更新按编号
            hisNurseMapper.updateOfListNid(list);
            //批量删除按编号只保留最早一条
            hisNurseMapper.deleteKeepOneByIdCard();
            hisNurseMapper.deleteKeepOneByNurseLicence();
            hisNurseMapper.deleteKeepOneBySeniority();
            hisNurseMapper.deleteKeepOneByNid();
        }
        return AjaxResult.success();
    }
//    @Override
//    public AjaxResult registerNurseSelect(HisNurse hisNurse) {
//        String msg = registerNurseSelectRule(hisNurse);
//        if(msg!=null){
//            return AjaxResult.error(msg);
//        }
//
//        if (StringUtils.isEmpty(hisNurse.getNurseId())) {
//            return AjaxResult.error("请选择护士！");
//        }
//        List<HisNurse> result2= hisNurseMapper.selectList(new LambdaQueryWrapper<HisNurse>().eq(HisNurse::getNurseId,hisNurse.getNurseId()).eq(HisNurse::getSignature,hisNurse.getSignature()));
//        //通过用户名判断 判断用户是否存在
//        String s = iUserService.checkUserNameUnique(hisNurse.getUsername());
//        if(!(s.equals(UserConstants.UNIQUE))){
//            return AjaxResult.error("用户名已经被注册了！");
//        }
//        //通过护士资格证号判断用户是否存在
//       List<SysUser> lsuser = iUserService.selectUserBySe(hisNurse.getNurseSeniority());
//        if(lsuser != null&&lsuser.size()>0){
//            return AjaxResult.error("护士已经被注册了！");
//        }
//        //密码加密
//        String password = SecurityUtils.encryptPassword(hisNurse.getPassword());
//        SysUser sysUser = new SysUser();
//        sysUser.setUserName(hisNurse.getUsername());
//        sysUser.setPassword(password);
//        sysUser.setUserType("9");
//        sysUser.setNurseSeniority(hisNurse.getNurseSeniority());
//        sysUser.setUpdateTime(new Date());
//
//        //向数据库里面插入数据
//        int j = iUserService.insertUser(sysUser);
//        //更新当前临时注册的字段
//        int i = 0;
//        if(result2==null){
//            //没有在his系统中的护士作插入操作
//            i = hisNurseMapper.insertHisNurse(hisNurse);
//        }else {
//            //在his系统中的医生作更新操作
//            for(HisNurse item :result2){
//                if(item.getId()!=null){
//                    hisNurse.setId(item.getId());
//                    hisNurseMapper.updateHisNurse(hisNurse);
//                }
//            }
//
//        }
//        return AjaxResult.success();
//    }

    @Override
    public AjaxResult registerNurseUnSelect(HisNurse hisNurse) {
        String msg = registerNurseSelectRule(hisNurse);
        if(msg!=null){
            return AjaxResult.error(msg);
        }

        if (StringUtils.isEmpty(hisNurse.getNurseId())) {
            return AjaxResult.error("请选择护士！");
        }
        List<HisNurse> result2= hisNurseMapper.selectList(new LambdaQueryWrapper<HisNurse>().eq(HisNurse::getIdCard,hisNurse.getIdCard()).eq(HisNurse::getSignature,hisNurse.getSignature()));
        //通过用户名判断 判断用户是否存在
        String s = iUserService.checkUserNameUnique(hisNurse.getUsername());
        if(!(s.equals(UserConstants.UNIQUE))){
            return AjaxResult.error("用户名已经被注册了！");
        }
        //通过护士资格证号判断用户是否存在
        List<SysUser> lsuser = iUserService.selectUserBySe(hisNurse.getNurseSeniority());
        if(lsuser != null&&lsuser.size()>0){
            return AjaxResult.error("护士已经被注册了！");
        }
        //密码加密
        String password = SecurityUtils.encryptPassword(hisNurse.getPassword());
        SysUser sysUser = new SysUser();
        sysUser.setUserName(hisNurse.getUsername());
        sysUser.setPassword(password);
        sysUser.setUserType("9");
        sysUser.setNurseSeniority(hisNurse.getNurseSeniority());
        sysUser.setUpdateTime(new Date());

        //向数据库里面插入数据
        int j = iUserService.insertUser(sysUser);
        //更新当前临时注册的字段
        int i = 0;
        if(result2==null){
            //没有在his系统中的护士作插入操作
            i = hisNurseMapper.insertHisNurse(hisNurse);
        }else {
            //在his系统中的医生作更新操作
            for(HisNurse item :result2){
                if(item.getId()!=null){
                    hisNurse.setId(item.getId());
                    hisNurseMapper.updateHisNurse(hisNurse);
                }
            }

        }
        return AjaxResult.success();

//        if (i > 0&& j > 0) {
//            List <HisNurse> olist =   hisNurseMapper.selectBySignatureIsNull(hisNurse.getNurseSeniority());
//            HisNurse ndata =  hisNurseMapper.selectBySignatureIsNotNull(hisNurse.getNurseSeniority());
//            for(HisNurse olddata:olist){
//                //如果旧的记录存在，则更新签名和doctor_code,并把新插入的那条记录删除
//                hisNurse.setId(olddata.getId());
//                hisNurseMapper.updateHisNurse(olddata);
//            }
//            if(olist.size()>0) {
//                //如果有老的数据，那这条新注册的数据就可以删除了
//                hisNurseMapper.deleteHisNurseById(ndata.getId());
//            }
//            return AjaxResult.success();
//        }else {
//            if(i != 0&& j == 0){
//                HisNurse ndata =  hisNurseMapper.selectBySignatureIsNotNull(hisNurse.getNurseSeniority());
//                hisNurseMapper.deleteHisNurseById(ndata.getId());
//            }else {
//                int del =iUserService.delByHosReg(sysUser.getNurseSeniority());
//            }
//            return AjaxResult.error("系统繁忙，稍后再试！");
//        }
    }
    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public HisNurse selectHisNurseById(Long id)
    {
        return hisNurseMapper.selectHisNurseById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param hisNurse 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<HisNurse> selectHisNurseList(HisNurse hisNurse)
    {
        return hisNurseMapper.selectHisNurseList(hisNurse);
    }

  @Override
    public List<HisNurse> selectnurTowlist(HisNurse hisNurse)
    {
        ArrayList<HisNurse> nur = new ArrayList<>();
        if (!StringUtils.isEmpty(hisNurse.getRegisterNumber())) {
            List<HisNurse> nurList = hisNurseMapper.selectByReg(hisNurse.getRegisterNumber());
            for (HisNurse nurse : nurList) {
                if (!nur.contains(nurse)) {
                    nur.add(nurse);
                }
            }
        }
        if (!StringUtils.isEmpty(hisNurse.getHospitalId())&& !StringUtils.isEmpty(hisNurse.getSignature())) {
            List<HisNurse> nurList = hisNurseMapper.selectBySigAndHos(hisNurse.getSignature(), hisNurse.getHospitalId());
            for (HisNurse nurse : nurList) {
                if (!nur.contains(nurse)) {
                    nur.add(nurse);
                }
            }
        }
        return nur;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param hisNurse 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertHisNurse(HisNurse hisNurse)
    {
        return hisNurseMapper.insertHisNurse(hisNurse);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param hisNurse 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateHisNurse(HisNurse hisNurse)
    {
        return hisNurseMapper.updateHisNurse(hisNurse);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteHisNurseByIds(Long[] ids)
    {
        return hisNurseMapper.deleteHisNurseByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteHisNurseById(Long id)
    {
        return hisNurseMapper.deleteHisNurseById(id);
    }






    @Override
    public List<HisNurse> selectOdsNurListBySig(String signature) {

        return hisNurseMapper.selectNurBySig(signature);
    }

    @Override
    public Integer checkSameName(String signature) {
        List<HisNurse> list1 = hisNurseMapper.selectNurBySig(signature);
        if(list1==null || list1.size()==0){
            return 1;
        }else {
            List<HisNurse> list = hisNurseMapper.checkSameName(signature);
            if(list==null || list.size()==0){
                return 0;
            }else{
                return 1;
            }
        }
    }

    /**
     * zj  护士导入
     * @param userList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importNurData(List<HisNurseExcelVo> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入机构数据不能为空！");
        }
        int successNum = 0; //统计成功的数据量
        int failureNum = 0; //统计失败的数据量
        StringBuilder successMsg = new StringBuilder(); //记录成功的数据信息
        StringBuilder failureMsg = new StringBuilder(); //记录失败的数据信息和错误信息
        for (HisNurseExcelVo user : userList)
        {
            try
            {
                if(org.apache.commons.lang3.StringUtils.isBlank(user.getNurselicence())){
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getNurselicence() + " 导入失败：";
                    failureMsg.append(msg);
                    break;
                }
                HisNurse u = this.hisNurseMapper.selectByLicence(user.getNurselicence());
                HisNurse hisNurse= new HisNurse();
                BeanUtils.copyProperties(user,hisNurse);
                if (StringUtils.isNull(u))
                {
                    this.hisNurseMapper.insertHisNurse(hisNurse);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getNurselicence() + " 导入成功");
                }
                else
                {
                    hisNurse.setId(u.getId());
                    this.updateHisNurse(hisNurse);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getNurselicence() + " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getNurselicence() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importData(List<HisNurseExcelVo> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入机构数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (HisNurseExcelVo user : userList)
        {
            try
            {
                if(org.apache.commons.lang3.StringUtils.isBlank(user.getNurselicence())){
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getNurselicence() + " 导入失败：";
                    failureMsg.append(msg);
                    break;
                }
                HisNurse u = this.hisNurseMapper.selectByLicence(user.getNurselicence());
                HisNurse odsHospitalAll= new HisNurse();
                BeanUtils.copyProperties(user,odsHospitalAll);
                if (StringUtils.isNull(u))
                {
                    this.hisNurseMapper.insertHisNurse(odsHospitalAll);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getNurselicence() + " 导入成功");
                }
                else
                {
                    this.updateHisNurse(odsHospitalAll);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getNurselicence() + " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getNurselicence() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
